package com.spit.fammo.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.TimeUtils
import com.blankj.utilcode.util.ToastUtils
import com.spit.amoeba.base.MyBaseViewModel
import com.spit.fammo.R
import com.spit.fammo.bean.DataBean
import com.spit.fammo.bean.db.StockTakeListBean
import com.spit.fammo.ext.ASSET_FAIL_PAGE
import com.spit.fammo.ext.ASSET_NOT_PAGE
import com.spit.fammo.ext.ASSET_STOCK_PAGE
import com.spit.fammo.ext.STATUSID_ASSET_10
import com.spit.fammo.ext.STATUSID_ASSET_2
import com.spit.fammo.ext.STATUSID_ASSET_9
import com.spit.fammo.network.apiService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import me.hgj.jetpackmvvm.base.appContext
import me.hgj.jetpackmvvm.callback.databind.StringObservableField
import me.hgj.jetpackmvvm.ext.requestNoCheck
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

/**
 * User: Nike
 *  2025/1/6 16:46
 */
class DownloadModel: MyBaseViewModel() {

    var stockTakename = StringObservableField(appContext.getString((R.string.stock_take)))
    var listStockTakeBean: MutableLiveData<DataBean> = MutableLiveData()

    fun onStock() {
        requestNoCheck({ apiService.stockTakeList() }, {
            viewModelScope.launch(Dispatchers.IO) {
                val nowString = TimeUtils.getNowString(TimeUtils.getSafeDateFormat("dd/MM/yyyy"))
                val dateFormat = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault())
                val itemsWithDates: List<Pair<StockTakeListBean, Date>> = it.mapNotNull {
                    try {
                        it to dateFormat.parse(it.endDate)
                    } catch (e: ParseException) {
                        null
                    }
                }
                val sortedItems = itemsWithDates.sortedByDescending { it.second }
                val nowDate: Date = dateFormat.parse(nowString)
                var total = 0
                sortedItems.forEach { (item, validDate) ->
                    if (validDate.compareTo(nowDate) >= 0) {
                        item.userId = userId
                        item.companyid = companyID
                        stockTakeListDao.add(item)
                        total += item.total
                    }
                }
                stockTakeListDao.findAll(userId).forEach {
                    stockTakeListAsset(it)
                }
                listStockTakeBean.postValue(DataBean(total = total))
            }
        }, {
            //请求失败 网络异常回调在这里
            loadingChange.dismissDialog
            ToastUtils.showShort(it.throwable!!.message)
            LogUtils.e(it.throwable)
        }, false)
    }

    private fun stockTakeListAsset(bean: StockTakeListBean) {
        val stocktakeno = bean.stocktakeno
        requestNoCheck({ apiService.stockTakeListAsset(stocktakeno) }, {
            viewModelScope.launch(Dispatchers.IO) {
                val data = it.data
                if (!data.isNullOrEmpty()){
                    data.forEach {
                        it.stocktakeno = stocktakeno
                        it.stocktakeName = bean.name
                        it.userId = userId
                        it.companyid = companyID
                        it.epc = if (it.epc.isNullOrEmpty()) "" else it.epc
                        it.type = when(it.statusid){
                            STATUSID_ASSET_2 -> ASSET_STOCK_PAGE
                            STATUSID_ASSET_10 -> ASSET_NOT_PAGE
                            STATUSID_ASSET_9 -> ASSET_FAIL_PAGE
                            else -> ASSET_FAIL_PAGE
                        }
                    }
                    assetDao.addAll(data)
                }
            }
        })
    }

}